package com.example.app.page;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.app.R;
import com.example.app.api.UploadService;
import com.example.app.config.RetrofitClient;
import com.example.app.entity.ReservationInfoRequest;
import com.example.app.entity.ReservationInfoResponse;
import com.example.app.entity.UploadResponse;
import com.example.app.event.RefreshBillEvent;
import com.example.app.event.SwitchTabEvent;
import com.example.app.manager.TokenManager;
import com.example.app.event.ParkingMapUpdateEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ReservationFragment extends Fragment {
    private EditText etSlotNumber;
    private Button btnConfirm;

    private TextView tvStartTime, tvEndTime;
    private Calendar startTime, endTime;
    private SimpleDateFormat dateFormat, timeFormat, datetimeFormat;

    private static final int PICK_IMAGE_REQUEST = 1;
    private Button btnSelectImage, btnUploadImage;
    private ImageView ivPreview;
    private TextView tvResult;
    private RetrofitClient retrofitClient;
    private TokenManager tokenManager;
    private Uri selectedImageUri;

    private String plateNumber;
    private String plateUrl;

    private String platePackId;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.reservation, container, false);

        etSlotNumber = view.findViewById(R.id.et_slot_number);
        btnConfirm = view.findViewById(R.id.btn_confirm);

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                platePackId = etSlotNumber.getText().toString();
                if (!TextUtils.isEmpty(platePackId)) {
                    try {
                        showToast("请根据实际情况判断车位是否可用");
                    } catch (NumberFormatException e) {
                        showToast("请输入有效的数字");
                    }
                } else {
                    showToast("请输入车位编号");
                }
            }
        });

        // 初始化日期时间格式
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        // 初始化日历实例
        startTime = Calendar.getInstance();
        endTime = Calendar.getInstance();
        endTime.add(Calendar.HOUR_OF_DAY, 1);

        // 绑定视图控件
        tvStartTime = view.findViewById(R.id.tv_start_time);
//        tvEndTime = view.findViewById(R.id.tv_end_time);
        Button btnSubmit = view.findViewById(R.id.btn_submit);

        // 设置初始时间文本
        updateDateTimeDisplay();

        // 设置时间选择器点击事件
        view.findViewById(R.id.layout_start_time).setOnClickListener(v -> showDateTimePicker(true));
//        view.findViewById(R.id.layout_end_time).setOnClickListener(v -> showDateTimePicker(false));

        // 设置提交按钮点击事件
        btnSubmit.setOnClickListener(v -> {
            if (isAllDataFilled()) {
                submitReservation();
            } else {
                showToast("请填写完整所有信息");
            }
        });

        // 初始化组件
        btnSelectImage = view.findViewById(R.id.btn_select_image);
        btnUploadImage = view.findViewById(R.id.btn_upload_image);
        ivPreview = view.findViewById(R.id.iv_preview);
        tvResult = view.findViewById(R.id.tv_result);

        // 初始化Retrofit客户端和Token管理器
        retrofitClient = RetrofitClient.getInstance(requireActivity().getApplication());
        retrofitClient = RetrofitClient.getInstance(requireActivity().getApplication());
        tokenManager = retrofitClient.getTokenManager();

        // 检查是否有Token
        if (tokenManager.getToken() == null) {
            showResult("未发现Token，请确保已在其他地方获取Token");
            btnUploadImage.setEnabled(false);
        }

        // 选择图片按钮点击事件
        btnSelectImage.setOnClickListener(v -> openGallery());

        // 上传图片按钮点击事件
        btnUploadImage.setOnClickListener(v -> uploadSelectedImage());

        return view;
    }

    private void showToast(String message) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }

    private void showDateTimePicker(final boolean isStartTime) {
        final Calendar calendar = isStartTime? startTime : endTime;

        // 日期选择器
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                requireContext(),
                (view, year, month, dayOfMonth) -> {
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, month);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                    // 时间选择器
                    TimePickerDialog timePickerDialog = new TimePickerDialog(
                            requireContext(),
                            (view1, hourOfDay, minute) -> {
                                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                calendar.set(Calendar.MINUTE, minute);
                                calendar.set(Calendar.SECOND, 0);

                                // 确保结束时间晚于开始时间
                                if (!isStartTime && endTime.before(startTime)) {
                                    endTime.setTimeInMillis(startTime.getTimeInMillis());
                                    endTime.add(Calendar.HOUR_OF_DAY, 1);
                                }

                                updateDateTimeDisplay();
                            },
                            calendar.get(Calendar.HOUR_OF_DAY),
                            calendar.get(Calendar.MINUTE),
                            true
                    );
                    timePickerDialog.show();
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    private void updateDateTimeDisplay() {
        tvStartTime.setText(datetimeFormat.format(startTime.getTime()));
    }

    private void submitReservation() {
        // 获取选择的开始时间和结束时间
        String startTimeStr = datetimeFormat.format(startTime.getTime());
        String endTimeStr = datetimeFormat.format(endTime.getTime());

        Log.d("ReservationFragment", "提交预订 - 开始时间: " + startTimeStr + ", 结束时间: " + endTimeStr);
        Log.d("ReservationFragment", "车牌：" + plateNumber + "图片地址" + plateUrl);
        Log.d("ReservationFragment", "用户ID：" + tokenManager.getUserId());
        Log.d("ReservationFragment", "车位ID：" + platePackId);

        // 创建预订请求对象
        ReservationInfoRequest reservationInfoRequest = new ReservationInfoRequest(
                startTimeStr,
                null,
                plateNumber,
                plateUrl,
                tokenManager.getUserId(),
                platePackId);

        UploadService reservationService = retrofitClient.getAuthService(UploadService.class);
        Call<ReservationInfoResponse> call = reservationService.reservation(reservationInfoRequest);

        call.enqueue(new Callback<ReservationInfoResponse>() {
            @Override
            public void onResponse(Call<ReservationInfoResponse> call, Response<ReservationInfoResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ReservationInfoResponse reservationResponse = response.body();
                    if (reservationResponse.isSuccess()) {
                        Log.e("ReservationFragment", "预定成功");
                        clearData();
                        EventBus.getDefault().post(new ParkingMapUpdateEvent());
                        EventBus.getDefault().post(new RefreshBillEvent());
                        EventBus.getDefault().post(new SwitchTabEvent(0));
                    } else {
                        // 预订失败，显示错误信息
                        showResult("预订失败: " + reservationResponse.getMessage());
                    }
                } else {
                    // HTTP错误处理
                    showResult("预订失败: HTTP " + response.code());
                    Log.e("ReservationFragment", "HTTP错误: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<ReservationInfoResponse> call, Throwable t) {
                // 网络请求失败处理
                showResult("网络错误: " + t.getMessage());
                Log.e("ReservationFragment", "网络请求失败: " + t.getMessage());
            }
        });
    }

    private void clearData() {
        etSlotNumber.setText("");
        plateNumber = "";
        plateUrl = "";
        platePackId = "";
        selectedImageUri = null;
        ivPreview.setImageURI(null);
        btnUploadImage.setEnabled(false);
        startTime = Calendar.getInstance();
        endTime = Calendar.getInstance();
        endTime.add(Calendar.HOUR_OF_DAY, 1);
        updateDateTimeDisplay();
    }

    private boolean isAllDataFilled() {
        return!TextUtils.isEmpty(plateNumber) &&!TextUtils.isEmpty(plateUrl) &&
                !TextUtils.isEmpty(platePackId) && selectedImageUri != null;
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            ivPreview.setImageURI(selectedImageUri);
            btnUploadImage.setEnabled(true);
        }
    }

    private void uploadSelectedImage() {
        if (selectedImageUri == null) {
            showResult("请先选择图片");
            return;
        }

        if (tokenManager.getToken() == null) {
            showResult("没有可用的Token，请确保已获取Token");
            return;
        }

        // 获取图片的真实路径
        String imagePath = getRealPathFromUri(selectedImageUri);
        if (imagePath == null) {
            showResult("无法获取图片路径");
            return;
        }

        File file = new File(imagePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
        RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "用户上传的图片");

        // 获取带Token的上传服务
        UploadService uploadService = retrofitClient.getAuthService(UploadService.class);
        Call<UploadResponse> call = uploadService.uploadImage(imagePart, description);

        call.enqueue(new Callback<UploadResponse>() {
            @Override
            public void onResponse(Call<UploadResponse> call, Response<UploadResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    UploadResponse uploadResponse = response.body();
                    if (uploadResponse.isSuccess()) {
                        plateNumber = uploadResponse.getPlateNumber();
                        plateUrl = uploadResponse.getUrl();
                        showResult("车牌识别为" + uploadResponse.getPlateNumber());
                    } else {
                        showResult("上传失败: " + uploadResponse.getMessage());
                    }
                } else if (response.code() == 401) {
                    showResult("认证失败，Token无效");
                } else {
                    showResult("上传失败: HTTP " + response.code());
                }
            }

            @Override
            public void onFailure(Call<UploadResponse> call, Throwable t) {
                showResult("网络错误: " + t.getMessage());
            }
        });
    }

    @SuppressLint("Range")
    private String getRealPathFromUri(Uri uri) {
        String result = null;
        Cursor cursor = requireActivity().getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            if (idx != -1) {
                result = cursor.getString(idx);
            }
            cursor.close();
        }
        return result;
    }

    private void showResult(String message) {
        if (isAdded()) {
            requireActivity().runOnUiThread(() -> tvResult.setText(message));
        }
    }
}